package com.shg.bean.bbs;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.shg.bean.Users;

/**
 * 收藏夹 
 * @author admin
 *收藏夹用于收藏作者、书籍、店铺
 *每用户都应该有一个收藏夹，所以和用户实体的关系为one-to-one
 *
 */
public class Favorite implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//ID号
	private String id;
	//收藏存储的内容
	private String content;
	//收藏主人
	private Users user;
	//伪劣
	private List<FavoriteItem> items;

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public Users getUser() {
		return user;
	}
	public void setUser(Users user) {
		this.user = user;
	}

	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public List<FavoriteItem> getItems() {
		return items;
	}
	public void setItems(List<FavoriteItem> items) {
		this.items = items;
	}
	/**
	 * 将数据库里面的String字符串转为数组 并存储在items
	 * @return
	 */
	public List<FavoriteItem> initItems(){
		items=new ArrayList<FavoriteItem>();
		//首先将内容转为数组
		JSONArray jsonArray=JSONArray.fromObject(this.content);
		List<FavoriteItem> buyItems = (ArrayList<FavoriteItem>) JSONArray.toList(jsonArray);
		//在将数组转为对象
		for(int i=0;i<buyItems.size();i++){
			JSONObject jsonObject=JSONObject.fromObject(buyItems.get(i));
			FavoriteItem item = (FavoriteItem) JSONObject.toBean(jsonObject, FavoriteItem.class);
			items.add(item);
		}
		return items;
	}
	/**
	 * 添加购物项
	 * @param item
	 */
	public boolean addItem(FavoriteItem item){
		boolean flag=false;
		if(this.items.contains(item)){
			this.items.remove(item);
			flag=true;
		}
		this.items.add(0, item);
		this.content=JSONArray.fromObject(this.items).toString();
		return flag;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Favorite other = (Favorite) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	
}
